package com.dc.handler.camera;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.dc.constat.SplConstants;
import com.dc.util.HttpClientUtil;
import com.dc.util.RedisUtil;
import com.dc.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description: TODO 视频流服务对接
 * @date: 2022/10/24 9:40
 * @author: zhang
 **/
@Slf4j
@Component
public class SplService {

    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取随机访问码 AccessCode
     */
    @Value("${spl.getAccess}")
    private String getAccess;

    /**
     * 用户名
     */
    @Value("${spl.userName}")
    private String userName;

    /**
     * 密码
     */
    @Value("${spl.password}")
    private String password;

    /**
     * 登录
     */
    @Value("${spl.login}")
    private String login;

    /**
     * 获取摄像头设备信息接口
     */
    @Value("${spl.getDeviceInfo}")
    private String getDeviceInfo;

    /**
     * 获取摄像头实时视频地址
     */
    @Value("${spl.getVideoRealtime}")
    private String getVideoRealtime;

    /**
     * 获取摄像头某时间段历史视频地址
     */
    @Value("${spl.getVideoHistory}")
    private String getVideoHistory;

    /**
     * 头部信息
     */
    private Map<String, Object> mapHeaders = new HashMap<>();

    /**
     * 信息加密
     */
    private Map<String, String> encryption() {
        Map<String, String> map = new HashMap<>(2);
        map.put("userId", DigestUtils.md5Hex(userName));
        String encode = Base64.encode(userName + init() + password);
        map.put("loginInfo", DigestUtils.md5Hex(encode));
        return map;
    }

    /**
     * 前置操作-获取随机验证码
     *
     * @return
     */
    private String init() {
        // 获取随机访问码
        Object o = redisUtil.get(SplConstants.ACCESS_CODE);
        if (null == o || StringUtils.isBlank(o.toString())) {
            // 随机访问码 五分钟有效期
            String accessCode = HttpClientUtil.doGet(getAccess);
            redisUtil.set(SplConstants.ACCESS_CODE, accessCode, 5, TimeUnit.MINUTES);
            return accessCode;
        }
        return o.toString();
    }

    /**
     * 登录
     *
     * @return
     */
    // @PostConstruct
    private String login() {
        try {
            Object token = redisUtil.get(SplConstants.ACCESS_TOKEN);
            if (null != token) {
                return token.toString();
            }
            // 拿到token 24小时有效期
            String resultToken = HttpClientUtil.doPost(login, encryption());
            redisUtil.set(SplConstants.ACCESS_TOKEN, resultToken, 24, TimeUnit.HOURS);
            return resultToken;
        } catch (Exception e) {
            log.info("视频流登录失败：[{}]", e.getMessage());
            return null;
        }
    }

    private void initHeaders() {
        mapHeaders = new HashMap<>();
        mapHeaders.put("Authorization", login());
    }

    /**
     * 获取摄像头设备信息
     *
     * @param page
     * @return
     */
    public String getDeviceInfo(int page) {
        // initHeaders();
        // 页数
        mapHeaders.put("page", page & 1);
        // return HttpClientUtil.doGet(getDeviceInfo, mapHeaders);

        String result = "{" +
                "\"pageNo\": 1," +
                "\"totalPages\": 15, " +
                "\"list\": [{ " +
                "\"deviceId\": \"184511\", " +
                "\"deviceType\": \"01\", " +
                "\"deviceCode\": \"T2-3F-D248#-010-H\"," +
                "\"deviceNo\": \"T2-3F-D223#-010-H\", " +
                "\"deviceName\": \"223廊桥登机桥通道01\", " +
                "\"address\": null, " +
                "\"serverNo\": \"401\", " +
                "\"videoType\": null, " +
                "\"ptzType\": \"0101\", " +
                "\"deviceModel\": \"04\", " +
                "\"operationType\": \"0201\", " +
                "\"manufacturer\": \"02\", " +
                "\"maintainer\": \"04\", " +
                "\"longitude\": \"124.99127197265625\", " +
                "\"latitude\": \"42.70565414428711\", " +
                "\"ipAddress\": \"10.196.97.52\", " +
                "\"usePort\": \"0\", " +
                "\"userName\": \"\", " +
                "\"userPwd\": \"\", " +
                "\"deviceStatus\": \"010201\", " +
                "\"deviceUseStatus\": \"01\", " +
                "\"floorCode\": \"0204\", " +
                "\"buildingCode\": \"02\", " +
                "\"isOnline\": \"010301\", " +
                "\"treeId\": \"51\", " +
                "\"voice\": \"0401\", " +
                "\"voiceName\": \"无\", " +
                "\"floorname\": \"T2航站楼三楼\", " +
                "\"ptzTypename\": \"枪机\", " +
                "\"deviceTypename\": \"视频\", " +
                "\"deviceStatusname\": \"正常\", " +
                "\"deviceUseStatusname\": null, " +
                "\"deviceIsOnlinename\": \"在线\", " +
                "\"manufacturername\": \"博世\", " +
                "\"serverName\": \"博世BVMS\", " +
                "\"serverFactory\": \"bosch\", " +
                "\"videoPlatformIp\": \"10.196.40.1\", " +
                "\"port\": \"0\", " +
                "\"storageIp\": \"10.196.40.12\", " +
                "\"storagePort\": null " +
                "}, " +
                "{ " +
                "\"deviceId\": \"184525\", " +
                "\"deviceType\": \"01\", " +
                "\"deviceCode\": \"T2-2F-D249#-011-I\", " +
                "\"deviceNo\": \"T2-2F-D222#-011-I\", " +
                "\"deviceName\": \"222廊桥顶部02\", " +
                "\"address\": null, " +
                "\"serverNo\": \"401\", " +
                "\"videoType\": null, " +
                "\"ptzType\": \"0102\", " +
                "\"deviceModel\": \"09\", " +
                "\"operationType\": \"0201\", " +
                "\"manufacturer\": \"02\", " +
                "\"maintainer\": \"04\", " +
                "\"longitude\": \"124.79542541503906\", " +
                "\"latitude\": \"42.758689880371094\", " +
                "\"ipAddress\": \"10.196.97.66\", " +
                "\"usePort\": \"0\", " +
                "\"userName\": null, " +
                "\"userPwd\": null, " +
                "\"deviceStatus\": \"010201\", " +
                "\"deviceUseStatus\": \"01\", " +
                "\"floorCode\": \"0204\", " +
                "\"buildingCode\": \"02\", " +
                "\"isOnline\": \"010301\", " +
                "\"treeId\": \"45\", " +
                "\"voice\": \"0401\", " +
                "\"voiceName\": \"无\", " +
                "\"floorname\": \"T2航站楼三楼\", " +
                "\"ptzTypename\": \"球机\", " +
                "\"deviceTypename\": \"视频\", " +
                "\"deviceStatusname\": \"正常\", " +
                "\"deviceUseStatusname\": null, " +
                "\"deviceIsOnlinename\": \"在线\", " +
                "\"manufacturername\": \"博世\", " +
                "\"serverName\": \"博世BVMS\", " +
                "\"serverFactory\": \"bosch\", " +
                "\"videoPlatformIp\": \"10.196.40.1\", " +
                "\"port\": \"0\", " +
                "\"storageIp\": \"10.196.40.12\", " +
                "\"storagePort\": null " +
                "} " +
                "] " +
                "}";
        return result;
    }

    /**
     * 获取摄像头实时视频地址
     * <p>
     * 示例：
     * {
     * "url":" rtsp://dGVzdDo1LQ==:827ccb0eea8a706c4c34a16891f84e7b@192.168.1.102:564/100100007"
     * }
     *
     * @param deviceCode 摄像机编码(摄相机识别号)
     * @return
     */
    public String getGetVideoRealtime(String deviceCode) {
        initHeaders();
        // 摄像机编码
        mapHeaders.put("deviceCode", deviceCode);
        String result = HttpClientUtil.doGet(getVideoRealtime, mapHeaders);

        // 数据解析
        JSONObject parseObj = JSONUtil.parseObj(result);
        Object url = parseObj.get("url");
        if (null != url) {
            // 需要将rtsp的地址 转码
            parseObj.put("url", "123");
            return JSONUtil.toJsonStr(parseObj);
        }
        parseObj.put("message", "实时视频获取失败");
        return JSONUtil.toJsonStr(parseObj);
    }

    /**
     * 获取摄像头某时间段历史视频地址
     * 示例：
     * { "url": "rtsp://10.180.239.171:8050/200100352.MPG?TIME_SLICE=20220601T152525Z20220801T152525Z&SessionID=5PAWk7HzzmtAo19IUSJdw"
     * }
     *
     * @param deviceCode 摄像机编码(摄相机识别号)
     * @param startTime  开始时间（精确到 时分秒）
     * @param endTime    结束时间（精确到 时分秒）
     * @return
     */
    public String getDeviceHistory(String deviceCode, String startTime, String endTime) {
        initHeaders();
        // 摄像机编码
        mapHeaders.put("deviceCode", deviceCode);
        // 开始-结束时间
        mapHeaders.put("startTime", startTime);
        mapHeaders.put("endTime", endTime);
        String result = HttpClientUtil.doGet(getVideoHistory, mapHeaders);

        // 数据解析
        JSONObject parseObj = JSONUtil.parseObj(result);
        Object url = parseObj.get("url");
        if (null != url) {
            // 需要将rtsp的地址 转码
            parseObj.put("url", "123");
            return JSONUtil.toJsonStr(parseObj);
        }
        parseObj.put("message", "历史视频地址获取失败");
        return JSONUtil.toJsonStr(parseObj);
    }
}
